<?php
/**
 * Displays an import form to allow for upload & process of reference file
 * Post back to this file + then creates reference items on page
 * Returns back to view.php
 * @copyright &copy; 2009 The Open University
 * @author j.platts@open.ac.uk
 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
 * @package resourcepage
 *//** */
GLOBAL $CFG;
require_once(dirname(__FILE__).'/module_resourcepage.php');
require_once(dirname(__FILE__).'/addreferences_form.php');
require_once($CFG->dirroot.'/local/references/convert/refxml.php');
require_once($CFG->dirroot.'/local/references/apibib/apibib_lib.php');
require_once($CFG->dirroot.'/local/references/linking.php');

//make an instance of our own class - (this file is in class so it's nice and neat!)

new resourcepage_addreferences();

class resourcepage_addreferences{

    private $module=NULL;
    private $resourcepage=NULL;
    //vars used from form
    private $id;
    private $uploaded='';
    private $sort=0;
    private $availablefrom=0;
    private $availableuntil=0;
    private $course=NULL;
    
    private $backbutton=false;

    /**
     * Checks for proper login + permissions etc
     * sets up form
     * If a submit,
     * @return nothing
     */
    public function __construct(){
        GLOBAL $COURSE;
        
        $module=module_resourcepage::$inst;
        $this->module=&$module;
        
        if(!confirm_sesskey()){
            print_error('confirmsesskeybad');
        }

        $id=required_param('id',PARAM_INT);    // Course Module ID
        $this->id=$id;

        $module->obtain_view_info($id,null,$cm,$course,$resourcepage);
        $this->resourcepage=$resourcepage;
        
        // Security checks
        $module->verify_edit_action($cm);

        $mform = new resourcepage_addreferences_form();
        //default 'action' for form is strip_querystring(qualified_me())
        if ($mform->is_cancelled()){
            //you need this section if you have a cancel button on your form
            //here you tell php what to do if your user presses cancel
            //probably a redirect is called for!
            $this->to_resourcepage();
            //http_redirect('view.php', array("id" => $id, "creating"=>1), true);
        } else if ($fromform=$mform->get_data()){
            //this branch is where you process validated data.

            //don't need to save file anywhere?
            //$destination_directory=$CFG->dataroot.'/'.$COURSE->id.'/moddata/resourcepage/';
            //$destination_directory=$CFG->dataroot.'/moddata/resourcepage/temp/';
            //$mform->save_files($destination_directory);
            //$newfilename = $mform->get_new_filename();

            $this->uploaded=$mform->get_file_content('attachment');

            $this->sort=optional_param('sorting',0,PARAM_INT);

            $this->availablefrom=optional_param('availablefrom',0,PARAM_INT);
            $this->availableuntil=optional_param('availableuntil',0,PARAM_INT);
            
            if(optional_param('backbroken','',PARAM_INT)==1){
                $this->backbutton=true;
            }
            
            //disadvantage of class, need to set vars so can be used in other functions
            $this->course=$course;
            $this->resourcepage=$resourcepage;
            
            try{
                $this->process_file();
                add_to_log($course->id,'resourcepage','addreferencefile','','Added references from file '.$mform->_upload_manager->files['attachment']['name'],$id);
                $this->to_resourcepage();
            }
            catch(Exception $e){
                print_error($e->getMessage(),'resourcepage','./view.php?id='.$this->id);
            }

        } else {
            // this branch is executed if the form is submitted but the data doesn't validate and the form should be redisplayed
            // or on the first display of the form.

            $title=get_string('reference_addtitle','resourcepage');
            // Show header
            $module->print_header($cm,$course,$resourcepage,$title,false,'',$mform->focus());
            print_heading_with_help($title, "reference", 'resourcepage');
            print_simple_box_start('center', '', '', 5, 'generalbox', 'resourcepage_reference');

            //put data you want to fill out in the form into array $toform here then :
            //$mform->set_data($toform);
            $form=$mform->_form;
            $form->addElement('hidden', 'id', $id);
            $mform->display();
            print_footer($course);
            print_simple_box_end();
            
            add_to_log($course->id,'resourcepage','view','','Import references form',$id);
        }

    }

    private function process_file(){
        //globals used by db connection to get refstyle for this resourcepage
        global $CFG, $db;
        
        //check conversion class exists
        if(!class_exists('refxml')){
            throw new Exception('reference_class_load');
        }
        //Work out file type + check valid

        //create convertor class with correct type
        $convertor=new refxml();

        //Step 1
        //Convert input file text using convert class to known xml structure
        $filetype=NULL;
        $filetype=$convertor->return_data_type(&$this->uploaded);
        //non-supported file type
        if($filetype==NULL){
            throw new Exception('reference_load');
        }

        if(!$data=$convertor->return_transform_in(&$this->uploaded,$filetype)){
            throw new Exception('reference_load');
        }
        
        //Step 2
        //sort based on form setting
        switch($this->sort){
            case 1: $convertor->sort_references(&$data,'author');
                break;
            case 2: $convertor->sort_references(&$data,'title');
                break;
            default:
                break;
        }

        //Step 3
        //Connect with Quick Bib and return array of reference titles
        //$this->resourcepage->refstyle
        //get the resourcepage referencing style
        
        if(!$teststyle=get_field('resourcepage','refstyle','id',$this->resourcepage->id)){
            $teststyle=0;
        }
        //convert refstyle from int into text
        $teststyle=apibib::$referencestyles[$teststyle]['string'];
        
        $refstring=$convertor->return_references($data,true);
        
        //get reference titles from quikbib
        $titles=apibib::getbib($refstring,$teststyle,'RefWorks XML');
        if(!is_array($titles)){
            $titles=array();
        }
        
        //Step 4
        //work through items, get weblink for each item, then add to db
        
        //first work out live date etc
        if(array_key_exists('day',$this->availablefrom)) {
            $livedate=
            round((make_timestamp($this->availablefrom['year'], $this->availablefrom['month'], $this->availablefrom['day'])-
            $this->course->startdate) / (24*60*60));
        } else {
            $livedate=null;
        }

        if(array_key_exists('day',$this->availableuntil)) {
            $removedate=
            round((make_timestamp($this->availableuntil['year'], $this->availableuntil['month'], $this->availableuntil['day'])-
            $this->course->startdate) / (24*60*60));
        } else {
            $removedate=null;
        }

        //get data for each item
        $alldata=$convertor->return_reference($data,array(),true,true);
        if($alldata===false){
            $alldata=array();
        }
        
        for($a=0,$max=count($alldata);$a<$max;$a++)
        {
            $thisdata=$alldata[$a];
            $document=DOMDocument::loadXML($thisdata); //prepare for creation of weblink
            $linking = linking::create_link($document); //create weblink
            
            $title='';
            if(array_key_exists($a,$titles)){
                $title=$titles[$a];
            }
            
            //description
            $desc = '';
            $notes = $document->getElementsByTagName('no');
            if($notes->length > 0){
                $noteval = $notes->item(0)->nodeValue;
                $desc = clean_text($noteval, FORMAT_HTML);
            }
            
            //**manual vars for testing**
            //$weblink="http://www.open.ac.uk/".$a;
            $weblink = $linking[0];
            
            //create "reference" item

            $this->add_ref_item($title,$thisdata,$weblink,$livedate,$removedate,$desc);
            
        }
        
    }

    /**
     * Calls function to add items to db
     * @param $title string - reference title
     * @param $data string - the xml data to be saved
     * @param $weblink string - optional url
     * @param $livedate int - calculated live date
     * @param $removedate int - calculated remove date
     * @return unknown_type
     */
    private function add_ref_item($title,$data,$weblink=null,$livedate,$removedate,$desc){
        //$title=htmlspecialchars($title,ENT_QUOTES,"UTF-8");
        $title=stripslashes(clean_param($title,PARAM_TEXT));
        
        //create "reference" item
        $i=$this->module->add_item('reference',true,$livedate,$removedate,null,$title,$desc,null,$weblink,null,null,null,null,$this->backbutton?'B':null,null,$data);

        $this->module->add_container_item($this->resourcepage->containerid,$i);
    }

    private function to_resourcepage(){
        redirect('view.php?id='.$this->id.'&creating=1');
    }
}

?>
